import {Injectable} from "@angular/core";
import {App, Keyboard, Platform} from "ionic-angular";
import {AppPopup} from "./popup";
import {UserService} from "../providers/user-service";
@Injectable()
export class AppExit {
    private backButtonPressed: boolean = false;
    private defaultHandle: any = '';

    constructor(private app: App,
                private popup: AppPopup,
                private keyboard: Keyboard,
                private userServ: UserService,
                private platform: Platform,) {
    }

    private addHandle() {
        if (this.defaultHandle !== '') {
            return;
        }
        this.defaultHandle = this.platform.backButton.observers.shift();
        this.platform.backButton.subscribe(() => {
            this.confirmExit();
        });
    }

    private removeHandle() {
        if (this.defaultHandle == '') {
            return;
        }
        if(this.keyboard.isOpen()){
            this.keyboard.close();
            return;
        }
        this.platform.backButton.observers.pop();
        this.platform.backButton.observers[0] = this.defaultHandle;
        this.defaultHandle = '';
    }

    private confirmExit() {
        if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
            console.log("再按一次退出应用==============");
            this.userServ.logout();
            this.platform.exitApp();
        } else {
            this.popup.toast('再按一次退出应用', 'bottom', 2000);
            this.backButtonPressed = true;
            let timer = setTimeout(() => {
                this.backButtonPressed = false;
                clearTimeout(timer);
            }, 2000);//2秒内没有再次点击返回则将触发标志标记为false
        }
    }

    init() {
        this.app.viewDidEnter.subscribe((viewCtrl) => {
            console.log('发生了viewDidEnter事件：',viewCtrl);
            if (viewCtrl.name == 'TabsPage'||viewCtrl.isOverlay) {
                return
            }
            if (viewCtrl.index == 0) {
                this.addHandle();
            } else {
                this.removeHandle();
            }
        });
    }
}
